package com.atguigu.lease.web.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@RequiredArgsConstructor
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    private final GraphInfoService graphInfoService;
    private final ApartmentFacilityService apartmentFacilityService;
    private  final ApartmentLabelService apartmentLabelService;
    private  final ApartmentFeeValueService apartmentFeeValueService;
    private final ApartmentInfoMapper apartmentInfoMapper;
    private  final FeeValueMapper feeValueMapper;
    //private  final RoomInfoMapper roomInfoMapper;
    private final GraphInfoMapper graphInfoMapper;
    private final LabelInfoMapper labelInfoMapper;
    private final FacilityInfoMapper facilityInfoMapper;
    @Override
    public void saveorupdateall(ApartmentSubmitVo apartmentSubmitVo) {
        boolean update = apartmentSubmitVo.getId() != null;
        Long id = apartmentSubmitVo.getId();
        saveOrUpdate(apartmentSubmitVo);
        if(update)
        {
            //配套信息
            Db.lambdaUpdate(ApartmentFacility.class)
                    .eq(ApartmentFacility::getApartmentId,id)
                    .remove();
            //图片
            Db.lambdaUpdate(GraphInfo.class)
                    .eq(GraphInfo::getItemType, ItemType.APARTMENT)
                    .eq(GraphInfo::getItemId,id)
                    .remove();
            //删除杂费
            Db.lambdaUpdate(ApartmentFeeValue.class)
                    .eq(ApartmentFeeValue::getApartmentId,id)
                    .remove();
            //删除标签
            Db.lambdaUpdate(ApartmentLabel.class)
                    .eq(ApartmentLabel::getApartmentId,id)
                    .remove();

            /*LambdaQueryChainWrapper<ApartmentFacility> lambdaQueryChainWrapper=new LambdaQueryChainWrapper<>();
            lambdaQueryChainWrapper.*/
        }
        //2插入数据
        //插入图片
        List<GraphInfo> graphInfos=new ArrayList<>();
        List<GraphVo> graphVos=apartmentSubmitVo.getGraphVoList();
        System.out.println(graphVos);
        if(!CollectionUtils.isEmpty(graphVos))
        {
            for (int i = 0; i < graphVos.size(); i++) {
                GraphInfo g=new GraphInfo();
                g.setItemId(apartmentSubmitVo.getId());
                g.setItemType(ItemType.APARTMENT);
                g.setUrl(graphVos.get(i).getUrl());
                g.setName(graphVos.get(i).getName());
                graphInfos.add(g);
            }
            graphInfoService.saveBatch(graphInfos);
        }
        //插入配套列表
        List<ApartmentFacility> apartmentFacilities=new ArrayList<>();
        List<Long> FacilityId=apartmentSubmitVo.getFacilityInfoIds();
        if(CollUtil.isNotEmpty(FacilityId))
        {
            for (Long l : FacilityId) {
                ApartmentFacility af=new ApartmentFacility();
                af.setApartmentId(apartmentSubmitVo.getId());
                af.setFacilityId(l);
                apartmentFacilities.add(af);
            }
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }
        //插入标签信息
        List<ApartmentLabel> apartmentLabels=new ArrayList<>();
        List<Long> apartlabel=apartmentSubmitVo.getLabelIds();
        if(CollUtil.isNotEmpty(apartlabel)){
        for (Long l : apartlabel) {
            ApartmentLabel apartmentLabel=new ApartmentLabel();
            apartmentLabel.setApartmentId(apartmentSubmitVo.getId());
            apartmentLabel.setLabelId(l);
            apartmentLabels.add(apartmentLabel);
        }
        apartmentLabelService.saveBatch(apartmentLabels);}
        //插入杂费信息
        List<ApartmentFeeValue> apartmentFeeValues=new ArrayList<>();
        List<Long> apartfee=apartmentSubmitVo.getFeeValueIds();
        if(CollUtil.isNotEmpty(apartfee)){
        for (Long l : apartfee) {
            ApartmentFeeValue ap=new ApartmentFeeValue();
            ap.setApartmentId(apartmentSubmitVo.getId());
            ap.setFeeValueId(l);
            apartmentFeeValues.add(ap);
        }
        apartmentFeeValueService.saveBatch(apartmentFeeValues);}
    }

    @Override
    public IPage<ApartmentItemVo> pageitem(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        //apartmentInfoMapper.pageitem(page,queryVo);
        return apartmentInfoMapper.pageItem(page,queryVo);
    }

    @Override
    public IPage<ApartmentItemVo> pageall(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        //查询所有数据
        List<ApartmentInfo> listapartmengt = lambdaQuery()
                .eq(queryVo.getCityId()!=null,ApartmentInfo::getCityId,queryVo.getCityId())
                .eq(queryVo.getDistrictId()!=null,ApartmentInfo::getDistrictId,queryVo.getDistrictId())
                .eq(queryVo.getProvinceId()!=null,ApartmentInfo::getProvinceId,queryVo.getProvinceId())
                .list();
        List<RoomInfo> listroom = Db.lambdaQuery(RoomInfo.class).list();
        List<LeaseAgreement> listrent = Db.lambdaQuery(LeaseAgreement.class).list();
        /*Map<Long,List<RoomInfo>> roomall=new HashMap<>();
        Map<Long,List<LeaseAgreement>> roomrent=new HashMap<>();
        //把分组变成id的map集合
        if(CollUtil.isNotEmpty(listroom))
        {
            roomall = listroom.stream().collect(Collectors.groupingBy(RoomInfo::getApartmentId));
        }
        if(CollUtil.isNotEmpty(listrent))
        {
            roomrent = listrent.stream().collect(Collectors.groupingBy(LeaseAgreement::getApartmentId));
        }
        //创建返回数据，遍历公寓集合和map
        List<ApartmentItemVo> li=new ArrayList<>();
        for (ApartmentInfo graphInfo : listapartmengt) {
            ApartmentItemVo l=new ApartmentItemVo();
            Long id = graphInfo.getId();
            l.setFreeRoomCount((long) (roomall.get(id).size()-roomrent.get(id).size()));
            //会出现size为空，需要添加判断
            l.setId(graphInfo.getId());
            l.setName(graphInfo.getName());
            l.setTotalRoomCount((long) roomall.get(id).size());
            l.setCityId(graphInfo.getCityId());
            l.setDistrictId(graphInfo.getDistrictId());
            l.setProvinceId(graphInfo.getProvinceId());
            l.setAddressDetail(graphInfo.getAddressDetail());
            l.setCityName(graphInfo.getCityName());
            li.add(l);
        }*/
        //建立map集合
        Map<Long,Long> roomall=new HashMap<>();
        Map<Long,Long> roomrent=new HashMap<>();
        for (ApartmentInfo graphInfo: listapartmengt) {
            roomall.put(graphInfo.getId(),0L);
            roomrent.put(graphInfo.getId(),0L);
        }
        //遍历数据，map改变
        for (RoomInfo roomInfo : listroom) {
            Long apartmentId = roomInfo.getApartmentId();
            roomall.put(apartmentId,roomall.get(apartmentId)+1);
        }
        for (LeaseAgreement leaseAgreement : listrent) {
            Long apartmentId = leaseAgreement.getApartmentId();
            roomrent.put(apartmentId,roomrent.get(apartmentId));
        }
        //创建返回数据，遍历公寓集合和map
        List<ApartmentItemVo> li=new ArrayList<>();
        for (ApartmentInfo graphInfo : listapartmengt) {
            ApartmentItemVo l=new ApartmentItemVo();
            l.setFreeRoomCount(roomall.get(graphInfo.getId())-roomrent.get(graphInfo.getId()));
            l.setId(graphInfo.getId());
            l.setName(graphInfo.getName());
            l.setTotalRoomCount(roomall.get(graphInfo.getId()));
            l.setCityId(graphInfo.getCityId());
            l.setDistrictId(graphInfo.getDistrictId());
            l.setProvinceId(graphInfo.getProvinceId());
            l.setAddressDetail(graphInfo.getAddressDetail());
            l.setCityName(graphInfo.getCityName());
            li.add(l);
        }
        return new IPage<ApartmentItemVo>() {
            @Override
            public List<OrderItem> orders() {
                return null;
            }

            @Override
            public List<ApartmentItemVo> getRecords() {
                return li;
            }

            @Override
            public IPage<ApartmentItemVo> setRecords(List<ApartmentItemVo> records) {
                return null;
            }

            @Override
            public long getTotal() {
                return 0;
            }

            @Override
            public IPage<ApartmentItemVo> setTotal(long total) {
                return null;
            }

            @Override
            public long getSize() {
                return 0;
            }

            @Override
            public IPage<ApartmentItemVo> setSize(long size) {
                return null;
            }

            @Override
            public long getCurrent() {
                return 0;
            }

            @Override
            public IPage<ApartmentItemVo> setCurrent(long current) {
                return null;
            }
        };
    }

    @Override
    public ApartmentDetailVo selectbyid(Long id) {
        ApartmentDetailVo ad=new ApartmentDetailVo();
        //公寓基本信息
        ApartmentInfo apartment = getById(id);
        ad.setName(apartment.getName());
        ad.setCityId(apartment.getCityId());
        ad.setId(apartment.getId());
        ad.setDistrictId(apartment.getDistrictId());
        ad.setAddressDetail(apartment.getAddressDetail());
        ad.setIntroduction(apartment.getIntroduction());
        ad.setProvinceName(apartment.getProvinceName());
        ad.setPhone(apartment.getPhone());
        ad.setProvinceId(apartment.getProvinceId());
        ad.setLongitude(apartment.getLongitude());
        //图片vo
        List<GraphInfo> listgraphinfo = Db.lambdaQuery(GraphInfo.class)
                .eq(GraphInfo::getItemType, ItemType.APARTMENT)
                .eq(GraphInfo::getItemId, id).list();
        List<GraphVo> g=BeanUtil.copyToList(listgraphinfo,GraphVo.class);
        ad.setGraphVoList(g);
        //杂费vo
        /*List<ApartmentFeeValue> listapfee = Db.lambdaQuery(ApartmentFeeValue.class).eq(ApartmentFeeValue::getApartmentId, id).list();
        List<Long> list1=new ArrayList<>();
        if(CollUtil.isNotEmpty(listapfee))
        {
             list1 = listapfee.stream().map(ApartmentFeeValue::getFeeValueId).toList();
            System.out.println(list1);
        }*/
        //执行sql调用mapper获取最终分表*/
        List<FeeValueVo> fees=apartmentInfoMapper.getfee(id);
        ad.setFeeValueVoList(fees);


        //5.查询FeeValue
        /*List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);
        ad.setFeeValueVoList(feeValueVoList);*/
        /*
        //value表按id查询对应value
        List<FeeValue> listFeek = Db.lambdaQuery(FeeValue.class).in(FeeValue::getId,list1).list();

        //按keyid转换成map集合
        Map<Long, List<FeeValue>> collect=new HashMap<>();
        if(CollUtil.isNotEmpty(listFeek))
        {
            collect = listFeek.stream().collect(Collectors.groupingBy(FeeValue::getFeeKeyId));
        }
        //获取keyset集合
        Set<Long> key=collect.keySet();*/
        //查找对应的key
        //查找标签
        List<LabelInfo> in = apartmentInfoMapper.getlabel(id);
        ad.setLabelInfoList(in);
        //查找配套关系
        List<FacilityInfo> in1 = apartmentInfoMapper.getfacility(id);
        ad.setFacilityInfoList(in1);
        return ad;
    }

    @Override
    public void removeByIdnew(Long id) {
        List<RoomInfo> list = Db.lambdaQuery(RoomInfo.class).eq(RoomInfo::getApartmentId, id).list();
        if(CollUtil.isNotEmpty(list))
        {
            System.out.println("list:"+list);
            throw new LeaseException(310,"请先删除房间");
            //终止删除，相应提示信息
        }
        /*LambdaQueryWrapper<RoomInfo> roomQueryWrapper = new LambdaQueryWrapper<>();
        roomQueryWrapper.eq(RoomInfo::getApartmentId, id);
        Long count = roomInfoMapper.selectCount(roomQueryWrapper);
        if (count > 0) {
            throw new leaseException(310,"请先删除房间");
        }*/
        removeById(id);
        Db.lambdaUpdate(ApartmentFacility.class)
                .eq(ApartmentFacility::getApartmentId,id)
                .remove();
        Db.lambdaUpdate(ApartmentLabel.class)
                .eq(ApartmentLabel::getApartmentId,id)
                .remove();
        Db.lambdaUpdate(ApartmentFeeValue.class)
                .eq(ApartmentFeeValue::getApartmentId,id)
                .remove();
        Db.lambdaUpdate(GraphInfo.class)
                .eq(GraphInfo::getItemType,ItemType.APARTMENT)
                .eq(GraphInfo::getItemId,id)
                .remove();


    }

    @Override
    public void updatestatus(Long id, ReleaseStatus status) {
        System.out.println("1");
        lambdaUpdate().eq(ApartmentInfo::getId,id)
                .set(ApartmentInfo::getIsRelease,status);
        System.out.println("2");
    }

    @Override
    public List<ApartmentInfo> listdistant(Long id) {
        return lambdaQuery().eq(ApartmentInfo::getDistrictId, id).list();
    }

    @Override
    public ApartmentDetailVo selectbyidnew(Long id) {
        //1.查询ApartmentInfo
        ApartmentInfo apartmentInfo = this.getById(id);
        if (apartmentInfo == null) {
            return null;
        }

        //2.查询GraphInfo
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.APARTMENT, id);

        //3.查询LabelInfo
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);

        //4.查询FacilityInfo
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);

        //5.查询FeeValue
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);

        ApartmentDetailVo adminApartmentDetailVo = new ApartmentDetailVo();

        BeanUtils.copyProperties(apartmentInfo, adminApartmentDetailVo);
        adminApartmentDetailVo.setGraphVoList(graphVoList);
        adminApartmentDetailVo.setLabelInfoList(labelInfoList);
        adminApartmentDetailVo.setFacilityInfoList(facilityInfoList);
        adminApartmentDetailVo.setFeeValueVoList(feeValueVoList);

        return adminApartmentDetailVo;
    }
}




